<template>
    <div style="width: 100%;">
        <!-- 搜索表单 -->
        <el-form :inline="true" ref="formRef" :model="formInline" class="demo-form-inline">
            <el-form-item label="部门名称">
                <el-select v-model="formInline.departmentName" placeholder="请选择部门" clearable>
                    <el-option v-for="item in departments.departmentList" :key="item.value" :label="item.label"
                        :value="item.label"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="培训时间">
                <el-date-picker style="width: 250px;" v-model="formInline.time" type="daterange" range-separator="至"
                    start-placeholder="开始时间" end-placeholder="结束时间" />
            </el-form-item>
            <el-form-item class="search">
                <el-button type="primary" :icon="Refresh" @click="resetFormInline">重置</el-button>
                <el-button type="primary" :icon="Search" @click="searchData">查询</el-button>
            </el-form-item>
        </el-form>
        <!-- 按钮组 -->
        <div class="btn-group">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="danger" @click="multipleDelete">删除</el-button>
        </div>
        <!-- 表格 -->
        <div class="table">
            <el-table :data="tableData" style="width: 100%" border height="420" show-overflow-tooltip
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" label="全选" />
                <el-table-column fixed label="索引" type="index" :index="indexMethod" align="center" width="55" />
                <el-table-column prop="department_name" label="部门名称" />
                <el-table-column prop="start_time" label="开始时间" :formatter="formatDate" />
                <el-table-column prop="end_time" label="结束时间" :formatter="formatDate" />
                <el-table-column prop="place" label="培训地点" />
                <el-table-column prop="remarks" label="备注" />
                <el-table-column fixed="right" label="操作" width="180">
                    <template #default="scope">
                        <el-button type="primary" @click="handleDetail(scope.row)">详情</el-button>
                        <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div class="pagination-wrapper">
            <el-pagination class="pagination" v-model:current-page="page.pageNum" v-model:page-size="page.pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="page.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 弹窗-新增 -->
        <el-dialog class="dialog" v-model="dialogVisibleAdd" title="新增" width="800" @close="handleCloseAdd">
            <el-form class="dialog-add-form" :inline="true" :model="dialogFormAdd" :rules="dialogFormAddRules"
                ref="dialogAddFormRef">
                <el-form-item label-width="120px" prop="department_name" label="部门名称">
                    <el-select v-model="dialogFormAdd.department_name" placeholder="请选择部门" clearable>
                        <el-option v-for="item in departments.departmentList" :key="item.value" :label="item.label"
                            :value="item.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label-width="120px" prop="start_time" label="开始时间">
                    <el-date-picker v-model="dialogFormAdd.start_time" type="datetime" placeholder="请选择开始时间" />
                </el-form-item>
                <el-form-item label-width="120px" prop="end_time" label="结束时间">
                    <el-date-picker v-model="dialogFormAdd.end_time" type="datetime" placeholder="请选择结束时间" />
                </el-form-item>
                <el-form-item label-width="120px" prop="place" label="培训地点">
                    <el-input v-model="dialogFormAdd.place" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label-width="120px" prop="content" label="培训内容">
                    <el-input style="width: 220px" type="textarea" v-model="dialogFormAdd.content" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label-width="120px" prop="remarks" label="备注">
                    <el-input style="width: 220px" v-model="dialogFormAdd.remarks" type="textarea" placeholder="请输入"
                        clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCloseAdd">取消</el-button>
                    <el-button type="primary" @click="handleAddTraining">
                        添加
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 弹窗-详情 -->
        <el-dialog class="dialog" v-model="dialogDetailVisible" title="详情" width="800" :close="handleDetailClose">
            <el-form class="dialog-form" :inline="true" :model="dialogDetailForm" ref="dialogDetailFormRef">
                <el-form-item label-width="120px" label="部门名称">
                    <el-input v-model="dialogDetailForm.department_name" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="开始时间">
                    <el-input v-model="dialogDetailForm.start_time" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="结束时间">
                    <el-input v-model="dialogDetailForm.end_time" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="培训地点">
                    <el-input v-model="dialogDetailForm.place" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="培训内容">
                    <el-input v-model="dialogDetailForm.content" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="备注">
                    <el-input style="width: 220px;" v-model="dialogDetailForm.remarks" type="textarea" clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDetailClose">关闭</el-button>
                    <el-button type="primary" @click="updateDetailDialog">
                        修改
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { queryDepartments, queryDepartmentTraining, addDepartmentTraining, deleteDepartmentTraining, updateDepartmentTraining } from '@/api/department';
import { timeProcessing } from '@/utils/date'
import dayjs from 'dayjs'

// 分页
const page = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0,
})

// 部门
const departments = reactive({
    departmentList: []
})

// 表单-搜索-数据
const formInline = reactive({
    departmentName: '',
    time: null,
})
const formRef = ref(null);

// 表格数据
const tableData = ref([])

// 多选-id
const ids = ref([]);

// 新增-弹窗
const dialogVisibleAdd = ref(false)
const dialogAddFormRef = ref(null)
const dialogFormAdd = reactive({})
const dialogFormAddRules = {
    department_name: [
        { required: true, message: '请选择部门', trigger: 'blur' },
    ],
    start_time: [
        { required: true, message: '请选择开始时间', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请选择开始时间'));
                    return;
                }

                const selectedDate = dayjs(value);
                const now = dayjs();

                if (selectedDate.isBefore(now, 'minute')) { // 精确到分钟比较
                    callback(new Error('开始时间必须大于当前时间'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ],
    end_time: [
        { required: true, message: '请选择结束时间', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请选择结束时间'));
                    return;
                }

                if (!dialogFormAdd.start_time) {
                    callback(new Error('请先选择开始时间'));
                    return;
                }

                const endDate = dayjs(value);
                const startDate = dayjs(dialogFormAdd.start_time);

                if (endDate.isSameOrBefore(startDate)) {
                    callback(new Error('结束时间必须大于开始时间'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ],
    place: [
        { required: true, message: '请输入培训地点', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入培训内容', trigger: 'blur' },
    ],
}

// 详情-弹窗
const dialogDetailVisible = ref(false)
const dialogDetailFormRef = ref(null)
const dialogDetailForm = reactive({})

// 索引
const indexMethod = (index) => {
    return page.pageSize * (page.pageNum - 1) + index + 1
}

// 表格多选
const handleSelectionChange = (val) => {
    ids.value = val.map(item => item.id);
}

const formatDate = (row, column, cellValue) => {
    return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
}

// 获取部门和职位
const getDepartments = async () => {
    try {
        const res = await queryDepartments();
        if (res.code === 0) {
            const departmentSet = new Set(departments.departmentList.map(d => d.label));
            res.data.list.forEach(item => {
                if (!departmentSet.has(item.department_name)) {
                    departments.departmentList.push({
                        value: item.department_name,
                        label: item.department_name
                    });
                    departmentSet.add(item.department_name);
                }
            });
        } else {
            ElMessage.error(res.msg);
        }
    } catch {
        console.log("请求失败");
    }
}

// 搜索
const searchData = async () => {
    const data = {
        departmentName: formInline.departmentName,
        startTimeStart: formInline.time ? timeProcessing(formInline.time[0], 'date') : '',
        startTimeEnd: formInline.time ? timeProcessing(formInline.time[1], 'date') : '',
        pageNum: page.pageNum,
        pageSize: page.pageSize,
    }
    try {
        const res = await queryDepartmentTraining(data);
        if (res.code === 0) {
            tableData.value = res.data.list;
            page.total = res.data.total;
        } else {
            ElMessage.error(res.msg);
        }
    } catch (error) {
        console.log("请求失败", error);
    }
}

// 重置
const resetFormInline = () => {
    formInline.departmentName = '';
    formInline.time = null;
    searchData();
}

// 新增
const handleAddTraining = () => {
    if (dialogAddFormRef.value) {
        dialogAddFormRef.value.validate(async (valid) => {
            if (!valid) return;

            const addData = {
                ...dialogFormAdd,
                start_time: dayjs(dialogFormAdd.start_time).format("YYYY-MM-DD HH:mm:ss"),
                end_time: dayjs(dialogFormAdd.end_time).format("YYYY-MM-DD HH:mm:ss")
            }

            try {
                const resAdd = await addDepartmentTraining(addData);
                if (resAdd.code === 0) {
                    ElMessage.success('新增成功！');
                    handleCloseAdd();
                    searchData();
                } else {
                    ElMessage.error('新增失败！');
                }
            } catch (error) {
                console.log("请求失败", error);
            }
        })
    }
}

// 删除
const handleDelete = (ids) => {
    const data = {
        ids: Array.isArray(ids) ? ids : [ids]
    };
    ElMessageBox.confirm('确认删除选中项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteDepartmentTraining(data);
            if (res.code === 0) {
                ElMessage.success('删除成功！');
                searchData();
            } else {
                ElMessage.error('删除失败！');
            }
        } catch (error) {
            console.log("请求失败", error);
        }
    }).catch(() => {
        console.log('取消删除');
    })
}

// 多选删除
const multipleDelete = () => {
    if (ids.value.length === 0) {
        ElMessage.warning('请选择要删除的培训记录！');
        return
    }
    handleDelete(ids.value)
}

// 修改
const updateDetailDialog = async () => {
    const data = {
        ...dialogDetailForm,
    }
    try {
        const res = await updateDepartmentTraining(data);
        if (res.code === 0) {
            ElMessage.success('修改成功！');
            handleDetailClose();
            searchData();
        } else {
            ElMessage.error('修改失败！');
        }
    } catch (error) {
        console.log("请求失败", error);
    }
}

// 新增-弹窗-打开
const handleAdd = () => {
    dialogVisibleAdd.value = true;
}

// 新增-弹窗-关闭
const handleCloseAdd = () => {
    dialogVisibleAdd.value = false;
    if (dialogAddFormRef.value) dialogAddFormRef.value.resetFields();
}

// 详情-弹窗-打开
const handleDetail = (row) => {
    dialogDetailVisible.value = true;
    dialogDetailForm.id = row.id;
    dialogDetailForm.department_name = row.department_name;
    dialogDetailForm.place = row.place;
    dialogDetailForm.content = row.content;
    dialogDetailForm.remarks = row.remarks;
    dialogDetailForm.start_time = dayjs(row.start_time).format('YYYY-MM-DD HH:mm:ss');
    dialogDetailForm.end_time = dayjs(row.end_time).format('YYYY-MM-DD HH:mm:ss');
}

// 详情-弹窗-关闭
const handleDetailClose = () => {
    dialogDetailVisible.value = false
    if (dialogDetailFormRef.value) dialogDetailFormRef.value.resetFields();
}

// 分页
const handleSizeChange = (val) => {
    page.pageSize = val
    searchData()
}

const handleCurrentChange = (val) => {
    page.pageNum = val
    searchData()
}

onMounted(() => {
    searchData();
    getDepartments();
})
</script>

<style lang="scss" scoped>
.demo-form-inline {
    padding: 10px 20px 0;
}

.demo-form-inline .el-input {
    --el-input-width: 150px;
}

.demo-form-inline .el-select {
    --el-select-width: 150px;
}

.btn-group {
    box-sizing: border-box;
    padding-right: 20px;
    margin-bottom: 5px;
    margin-top: -15px;
    float: right;
}

.table {
    box-sizing: border-box;
    padding: 0 20px 0 15px;
}

.footer {
    position: relative;
    width: 100%;
    height: auto;
}

.pagination-wrapper {
    width: 100%;
    height: 44px;
    display: flex;
    justify-content: flex-end;
}

.pagination {
    margin-top: 15px;
    margin-right: 20px;
}

:deep(.el-dialog__body) {
    display: flex;
    justify-content: center;
}

.dialog-form {
    .el-input {
        --el-input-width: 220px;
    }
}

.dialog-add-form {
    .el-input {
        --el-input-width: 220px;
    }

    .el-select {
        --el-select-width: 220px;
    }
}
</style>
